package martingale

import (
	"database/sql"
	"encoding/json"
	"log"
)

type Storage struct {
	db *sql.DB
}

func NewStorage(db *sql.DB) *Storage {
	return &Storage{db: db}
}

func (s *Storage) Save(plan *Plan) error {
	if s.db == nil {
		return nil
	}

	data, err := json.Marshal(plan)
	if err != nil {
		return err
	}

	status := "active"
	if plan.Completed {
		status = "completed"
	}

	query := `
		INSERT INTO martingale_plans (id, symbol, status, plan_json, updated_at)
		VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
		ON CONFLICT(id) DO UPDATE SET
			status = excluded.status,
			plan_json = excluded.plan_json,
			updated_at = CURRENT_TIMESTAMP
	`
	_, err = s.db.Exec(query, plan.ID, plan.Symbol, status, string(data))
	return err
}

func (s *Storage) LoadAll() ([]*Plan, error) {
	if s.db == nil {
		return []*Plan{}, nil
	}

	// 加载所有计划（包含已完成的），这样前端可以展示历史计划
	query := `SELECT plan_json FROM martingale_plans ORDER BY updated_at DESC`
	rows, err := s.db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var plans []*Plan
	for rows.Next() {
		var data string
		if err := rows.Scan(&data); err != nil {
			log.Printf("Failed to scan plan: %v", err)
			continue
		}
		var plan Plan
		if err := json.Unmarshal([]byte(data), &plan); err != nil {
			log.Printf("Failed to unmarshal plan: %v", err)
			continue
		}
		plans = append(plans, &plan)
	}
	return plans, nil
}

func (s *Storage) Delete(planID string) error {
	if s.db == nil {
		return nil
	}
	_, err := s.db.Exec("DELETE FROM martingale_plans WHERE id = ?", planID)
	return err
}
